package com.android.internet;

import java.io.IOException; 
import java.io.InputStream; 
import java.util.ArrayList; 
import java.util.List; 

import javax.xml.parsers.ParserConfigurationException; 
import javax.xml.parsers.SAXParser; 
import javax.xml.parsers.SAXParserFactory; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.params.HttpConnectionParams; 
import org.apache.http.protocol.HTTP; 
import org.xml.sax.Attributes; 
import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 
import org.xml.sax.XMLReader; 
import org.xml.sax.helpers.DefaultHandler; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.Bundle; 
import android.os.Looper; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import com.android.internet.R; 

public class Login extends Activity { 
    private static final String UPDATE_URL = "http://10.0.2.2/Login/Login.php"; 
    public ProgressDialog progressDialog; 
    private EditText UserEditText; 
    private EditText PassEditText; 
    
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 

        progressDialog = new ProgressDialog(this); 
        progressDialog.setMessage("Please wait..."); 
        progressDialog.setIndeterminate(true); 
        progressDialog.setCancelable(false); 
        
        UserEditText = (EditText) findViewById(R.id.username); 
        PassEditText = (EditText) findViewById(R.id.password); 
        
        Button button = (Button) findViewById(R.id.okbutton); 
        button.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v) { 
                int usersize = UserEditText.getText().length(); 
                int passsize = PassEditText.getText().length(); 
                if(usersize > 0) { 
                    progressDialog.show(); 
                    String user = UserEditText.getText().toString(); 
                    String pass = PassEditText.getText().toString(); 
                    doLogin(user, pass); 
                } else createDialog("Error","Please enter Username and Password"); 
            } 
        }); 
        
        button = (Button) findViewById(R.id.cancelbutton); 
        button.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v) { quit(false, null); } 
        }); 
    } 

    private void quit(boolean success, Intent i) { 
        setResult( (success) ? -1:0, i); 
        finish(); 
    } 
    
    private void createDialog(String title, String text) { 
        AlertDialog ad = new AlertDialog.Builder(this) 
        .setPositiveButton("Ok", null) 
        .setTitle(title) 
        .setMessage(text) 
        .create(); 
        ad.show(); 
    } 
    
    private void doLogin(final String login, final String pass) { 
        Thread t = new Thread() { 
            public void run() { 
                Looper.prepare(); 
                DefaultHttpClient client = new DefaultHttpClient(); 
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);                 
                HttpResponse response; 
                HttpEntity entity;         
                try { 
                    HttpPost post = new HttpPost(UPDATE_URL); 
                    List <NameValuePair> nvps = new ArrayList <NameValuePair>(); 
                    nvps.add(new BasicNameValuePair("username", login)); 
                    nvps.add(new BasicNameValuePair("password", pass)); 
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded"); 
                    post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); 
                    response = client.execute(post); 
                    entity = response.getEntity(); 
                    InputStream is = entity.getContent(); 
                    read(is); 
                    is.close(); 
                    if (entity != null) entity.consumeContent(); 
                } catch (Exception e) { 
                    progressDialog.dismiss(); 
                    createDialog("Error", "Couldn't establish a connection"); 
                } 
                Looper.loop();                 
            } 
        }; 
        t.start(); 
    } 
    
    private void read(InputStream in) { 
        SAXParserFactory spf = SAXParserFactory.newInstance(); 
        SAXParser sp; 
        try { 
            sp = spf.newSAXParser(); 
            XMLReader xr = sp.getXMLReader(); 
            LoginContentHandler uch = new LoginContentHandler(); 
            xr.setContentHandler(uch); 
            xr.parse(new InputSource(in)); 
        } catch (ParserConfigurationException e) { 
        } catch (SAXException e) { 
        } catch (IOException e) {} 
    }     
    
    
    private class LoginContentHandler extends DefaultHandler { 
        private boolean in_loginTag = false; 
        private int userID; 
        private boolean error_occured = false; 

        public void startElement(String n, String l, String q, Attributes a) 
            throws SAXException 
        { 
            if(l == "login") in_loginTag = true;   
            if(l == "error") { 
                progressDialog.dismiss(); 
                if(Integer.parseInt(a.getValue("value")) == 1) 
                    createDialog("Error", "Couldn't connect to Database"); 
                if(Integer.parseInt(a.getValue("value")) == 2) 
                    createDialog("Error", "Error in Database: Table missing"); 
                if(Integer.parseInt(a.getValue("value")) == 3) 
                    createDialog("Error", "Invalid username and/or password"); 
                error_occured = true; 
            } 
            if(l == "user" && in_loginTag && a.getValue("id") != "")             
                userID = Integer.parseInt(a.getValue("id")); 
        } 
          
        public void endElement(String n, String l, String q) throws SAXException { 
            if(l == "login") { 
                in_loginTag = false; 
                if(!error_occured) { 
                    progressDialog.dismiss(); 
                    Intent i = new Intent(); 
                    i.putExtra("userid", userID); 
                    quit(true,i); 
                } 
            } 
        } 
          
        public void characters(char ch[], int start, int length) { } 
        public void startDocument() throws SAXException { } 
        public void endDocument() throws SAXException { } 
    }     
}